import React, { Component } from 'react'

import { inject, observer } from 'mobx-react/native'
import { graphql } from 'react-apollo'
import gql from 'graphql-tag'

import moment from 'moment'
import { Dimensions, ScrollView, StyleSheet } from 'react-native'
import { List, Toast, Stepper, WhiteSpace } from 'antd-mobile'
import { WhiteButton } from '../components'

import client from '../client'
import store from '../store'

const { Item } = List
const { Brief } = Item

const CREATE_ORDER = gql`
  mutation($customerId: ID!, $items: [OrderitemsOrderItem!]!) {
    createOrder(customerId: $customerId, items: $items, state: ONGOING) {
      id
    }
  }
`

@graphql(CREATE_ORDER, { name: 'createOrder' })
@observer
export class CartScreen extends Component {
  render = () =>
    store.cart.length === 0 ? (
      <Item>Empty Cart</Item>
    ) : (
      <ScrollView style={styles.container}>
        <List>
          {store.cart.length === 0 ? (
            <Item>Empty Cart</Item>
          ) : (
            store.cart.map(({ item, amount }) => (
              <Item
                key={item.id}
                wrap
                extra={
                  <Stepper
                    min={1}
                    value={amount}
                    onChange={n => store.actions.setCartItemAmount(item, n)}
                  />
                }
              >
                {item.title}
              </Item>
            ))
          )}
        </List>
        <WhiteSpace />
        <WhiteButton
          title="Clear Cart"
          onPress={() => {
            store.actions.clearCart()
            Toast.success('Success', 1, undefined, false)
          }}
        />
        <WhiteSpace />
        <WhiteButton
          title="Submit Order"
          onPress={async () => {
            trace('cart')(store.cart)
            const { createOrder } = this.props
            const response = await createOrder({
              variables: {
                customerId: store.user.id,
                items: store.cart.map(({ item, amount }) => ({
                  itemId: item.id,
                  amount,
                })),
              },
            })
            store.actions.clearCart()
            Toast.success('Submitted', 1, undefined, false)
          }}
        />
      </ScrollView>
    )
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
})
